# -*- coding: utf-8 -*-
import os
import json
import importlib
from flask import request
import function.mysql_util as db
from minio import Minio
from minio.error import ResponseError


def update_plugin(dir, name):
    if dir is None or name is None:
        return "failed"
    if file_exists(dir, name):
        dirname = os.path.dirname(__file__)
        plugin = "%s/plugin/%s/%s" % (dirname, dir, name)
        os.remove(plugin)
    return "success"


def handle():
    """handle a request to the function
    Args:
        req (str): request body
        Examples:
        {
          "language": "python",
          "endpoint": "main.py",
          "bucketName": "mymusic",
          "dsId": 1,
          "stdin": []
        }
    """
    req = request.get_json()
    print(req)

    if "language" not in req.keys() or req["language"] != "mysql":
        raise Exception("not suport language: %s" % req["language"])

    if "dsId" not in req.keys():
        raise Exception("dsId can not be None")

    if "endpoint" not in req.keys():
        raise Exception("endpoint can not be None")

    if "bucketName" not in req.keys():
        raise Exception("bucketName can not be None")

    endpoint = req["endpoint"]
    bucket_name = req["bucketName"]
    if file_exists(bucket_name, endpoint) is False:
        load_minio_obj(bucket_name, endpoint)

    ds_id = req["dsId"]

    result = run(ds_id, bucket_name, endpoint, request)

    if not isinstance(result, dict):
        raise Exception("result must be json")

    return json.dumps(result)


def print_result(result, stderr=None, error=None):
    return {
        "stdout": result,
        "stderr": stderr,
        "error":  error,
    }


def run(ds_id, bucket_name, fname, reload=False):
    try:
        module_name = "function.plugin.%s.%s" % (bucket_name, fname[:-3])
        exist = importlib.util.find_spec(module_name)
        module = importlib.import_module('.plugin.%s.%s' % (bucket_name, fname[:-3]), package='function')
        if exist is not None or reload is True:
            module = importlib.reload(module)
    except Exception as err:
        raise err
    connect = db.MysqlPoolHandler().load_connetc(ds_id).getConn()
    try:
        res = module.run(request, connect)
    except Exception as err:
        print(err)
        return {"err": "exec plugin failed"}
    finally:
        connect.dispose()
    return res


def file_exists(bucket_name, fname):
    dirname = os.path.dirname(__file__)
    plugin = "%s/plugin/%s/%s" % (dirname, bucket_name, fname)
    return os.path.isfile(plugin)


def load_minio_obj(bucket_name, filename):
    """
    Examples:
        load_minio_obj("foobar", "test/main.py")
    :param bucket_name: Bucket to read object from.
    :param filename: Object to read object from.
    """
    # 使用endpoint、access key和secret key来初始化minioClient对象。 secret_key  endpoint access_key secret_key
    endpoint = os.getenv('mio-endpoint')
    access_key = os.getenv('mio-access')
    secret_key = os.getenv('mio-secret')
    minio_client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=False)

    try:
        exist = minio_client.bucket_exists(bucket_name)
    except ResponseError as err:
        raise err

    if exist is False:
        raise Exception("target bucket is not exists")

    try:
        dirname = os.path.dirname(__file__)
        stat = minio_client.fget_object(bucket_name, filename, "%s/plugin/%s/%s" % (dirname, bucket_name, filename))
        print(stat)
    except ResponseError as err:
        raise err

